<script setup>
import axios from 'axios';

// 搜索状态和结果数据
const searchQuery = ref('');
const users = ref([]);
const totalUsers = ref(0);
const isLoading = ref(false);
const error = ref('');
const hasSearched = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// GitHub API 配置
const API_BASE_URL = 'https://api.github.com';

// 搜索用户函数
async function searchUsers() {
  // 输入验证
  if (!searchQuery.value.trim()) {
    error.value = '请输入有效的用户名';
    return;
  }

  // 重置状态
  isLoading.value = true;
  error.value = '';
  hasSearched.value = true;
  currentPage.value = 1;


  try {
    const response = await axios.get(`${API_BASE_URL}/search/users`, {
      params: {
        q: searchQuery.value.trim(),
        per_page: 100,
        page: 1
      },
      timeout: 10000, // 10秒超时
      headers: {
        'Accept': 'application/vnd.github.v3+json'
      }
    });

    // 更新结果数据
    users.value = response.data.items || [];
    totalUsers.value = Math.min(response.data.total_count || 0, 100); // 限制显示总数不超过实际获取的数量

    // 处理GitHub API速率限制
    if (response.headers['x-ratelimit-remaining'] === '0') {
      const resetTime = new Date(parseInt(response.headers['x-ratelimit-reset']) * 1000);
      error.value = `API速率限制已达，将在 ${resetTime.toLocaleTimeString()} 重置`;
    }
  } catch (err) {
    // 错误处理
    if (err.response) {
      switch (err.response.status) {
        case 403:
          error.value = 'API速率限制已达，请稍后再试';
          break;
        case 422:
          error.value = '搜索条件无效，请检查输入';
          break;
        case 500:
          error.value = 'GitHub服务器暂时不可用，请稍后再试';
          break;
        default:
          error.value = `请求失败: ${err.response.status} ${err.response.statusText}`;
      }
    } else if (err.request) {
      error.value = '网络错误，请检查您的网络连接';
    } else {
      error.value = '请求配置错误';
    }
  } finally {
    isLoading.value = false;
  }
}

// 清除错误信息
function clearError() {
  error.value = '';
}

// 查看用户个人资料
function viewUserProfile(url) {
  window.open(url, '_blank');
}


// 分页处理函数 - 从本地数组读取数据
function handleSizeChange(size) {
  pageSize.value = size;
  currentPage.value = 1; // 切换每页条数时重置为第一页
}

function handleCurrentChange(page) {
  currentPage.value = page;
}
</script>
<template>
  <div class="github-search-container">
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="请输入GitHub用户名"
        class="search-input"
        @keyup.enter="searchUsers"
      >
        <template #append>
          <el-button
            type="primary"
            @click="searchUsers"
            :loading="isLoading"
          >
            <el-icon>
              <i-ep-search />
            </el-icon>
            搜索
          </el-button>
        </template>
      </el-input>
    </div>

    <div class="results-section">
      <!-- 未搜索状态 -->
      <div
        v-if="!hasSearched"
        class="welcome-message"
      >
        <el-empty description="欢迎使用 GitHub 用户搜索工具" />
        <p class="welcome-tip">输入用户名并按回车键或点击搜索按钮开始搜索</p>
      </div>

      <!-- 加载中状态 -->
      <div
        v-else-if="isLoading"
        class="loading-message"
        v-loading="true"
        element-loading-text="正在搜索用户..."
      >
      </div>

      <!-- 请求失败状态 -->
      <div
        v-else-if="error"
        class="error-message"
      >
        <el-alert
          :title="'搜索失败: ' + error"
          type="error"
          show-icon
          closable
          @close="clearError"
        />
      </div>

      <!-- 请求成功状态 -->
      <div
        v-else-if="users.length > 0"
        class="users-grid"
      >
        <div
          v-for="user in users.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
          :key="user.id"
          class="user-card"
          @click="viewUserProfile(user.html_url)"
        >
          <div class="user-avatar">
            <img
              :src="user.avatar_url"
              :alt="user.login"
              loading="lazy"
            />
          </div>
          <div class="user-info">
            <h3 class="user-name">{{ user.login }}</h3>
          </div>
          <div class="user-actions">
            <el-button
              type="text"
              size="small"
              :href="user.html_url"
              target="_blank"
              :title="'访问 ' + user.login + ' 的 GitHub 主页'"
            >
              <el-icon>
                <i-ep-Link />
              </el-icon>
            </el-button>
          </div>
        </div>
      </div>

      <!-- 无结果状态 -->
      <div
        v-else-if="hasSearched && !isLoading && users.length === 0"
        class="no-results"
      >
        <el-empty description="未找到匹配的用户" />
        <p class="no-results-tip">请尝试其他用户名或检查拼写</p>
      </div>
    </div>

    <!-- 分页控件 -->
    <div
      v-if="totalUsers > 0 && !isLoading && !error"
      class="pagination"
    >
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>



<style scoped>
.github-search-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}



.search-section {
  max-width: 600px;
  margin: 0 auto 30px;
}

.search-input {
  width: 100%;
}

.results-section {
  margin-bottom: 30px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.welcome-message,
.loading-message,
.error-message,
.no-results {
  text-align: center;
  height: 400px;
}

.welcome-tip,
.no-results-tip {
  margin-top: 16px;
  color: #7f8c8d;
}


.users-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  padding-top: 20px;
  height: 400px;
  overflow-y: auto;
  scrollbar-width: none;
}

.user-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #e1e8ed;
  border-radius: 8px;
  background-color: #fff;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 100px;
  width: 400px;
}

.user-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #3498db;
}

.user-avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 16px;
  border: 2px solid #ecf0f1;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.user-card:hover .user-avatar img {
  transform: scale(1.1);
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #2c3e50;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}


.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .github-search-container {
    padding: 15px;
  }

  .search-header h2 {
    font-size: 24px;
  }

  .users-grid {
    grid-template-columns: 1fr;
  }

  .user-card {
    padding: 12px;
  }

  .user-avatar {
    width: 50px;
    height: 50px;
  }

  .user-name {
    font-size: 16px;
  }
}
</style>
